package com.chenhy.controller;

import com.chenhy.pojo.CommonResult;
import com.chenhy.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;


    @GetMapping("/getCaptchaImg")
    public void getCaptchaImg(HttpServletRequest request, HttpServletResponse response){
        ServletOutputStream os = null;
        response.setContentType("image/png");

        try {
            os = response.getOutputStream();
            ImageIO.write(captchaService.getCaptchaImg(request), "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/verify")
    public CommonResult verify(HttpServletRequest request, String captcha){

        String captchaUUID = request.getSession().getAttribute("CaptchaUUID").toString();

        CommonResult result = captchaService.verify(captchaUUID, captcha);

        return result;
    }


}
